import React, { useState, useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Layout } from 'antd';
import Login from './components/Auth/Login';
import Register from './components/Auth/Register';
import MainLayout from './components/Navigation/MainLayout';
import ErrorBoundary from './components/ErrorBoundary/ErrorBoundary';
import authService from './services/AuthService';
import { handleApiError } from './utils/errorHandler';
import './utils/globalErrorHandler';
import './styles/App.css';
import AuthPage from './components/Auth/AuthPage';

const { Content } = Layout;

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 检查用户是否已登录
    const checkAuth = async () => {
      try {
        const token = localStorage.getItem('token');
        if (token) {
          console.log('检查token有效性:', token.substring(0, 20) + '...');
          const isValid = await authService.validateToken(token);
          console.log('Token验证结果:', isValid);
          setIsAuthenticated(isValid);
          if (!isValid) {
            console.log('Token无效，清除本地存储');
            localStorage.removeItem('token');
          }
        } else {
          console.log('未找到token');
          setIsAuthenticated(false);
        }
      } catch (error) {
        console.error('认证检查失败:', error);
        // 静默处理认证检查错误，不显示错误消息
        handleApiError(error, '认证检查', false);
        localStorage.removeItem('token');
        setIsAuthenticated(false);
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, []);

  const handleLogin = (token, user) => {
    localStorage.setItem('token', token);
    localStorage.setItem('user', JSON.stringify(user));
    setIsAuthenticated(true);
  };

  const handleLogout = () => {
    // 清除所有用户的个性化推荐缓存
    // 获取所有localStorage键
    const keys = Object.keys(localStorage);
    
    // 筛选出个性化推荐相关的键并删除
    keys.forEach(key => {
      if (key.startsWith('personalizedRecommendations_') || key.startsWith('lastUserPreferences_')) {
        localStorage.removeItem(key);
      }
    });
    
    // 清除用户认证信息
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setIsAuthenticated(false);
  };

  return (
    <ErrorBoundary>
      <Layout style={{ minHeight: '100vh' }}>
        {loading ? (
          <div style={{ 
            display: 'flex', 
            justifyContent: 'center', 
            alignItems: 'center', 
            height: '100vh' 
          }}>
            <div>加载中...</div>
          </div>
        ) : (
          <Routes>
            <Route 
              path="/auth" 
              element={<AuthPage />}
            >
              <Route 
                path="login" 
                element={
                  isAuthenticated ? 
                    <Navigate to="/" replace /> : 
                    <ErrorBoundary>
                      <Login onLogin={handleLogin} />
                    </ErrorBoundary>
                } 
              />
              <Route 
                path="register" 
                element={
                  isAuthenticated ? 
                    <Navigate to="/" replace /> : 
                    <ErrorBoundary>
                      <Register />
                    </ErrorBoundary>
                } 
              />
            </Route>
            
            {/* 添加重定向保持兼容性 */}
            <Route 
              path="/login" 
              element={<Navigate to="/auth/login" replace />} 
            />
            <Route 
              path="/register" 
              element={<Navigate to="/auth/register" replace />} 
            />
            
            <Route 
              path="/*" 
              element={
                isAuthenticated ? 
                  <ErrorBoundary>
                    <MainLayout onLogout={handleLogout} />
                  </ErrorBoundary> : 
                  <Navigate to="/auth/login" replace />
              } 
            />
          </Routes>
        )}
      </Layout>
    </ErrorBoundary>
  );
}

export default App;